# Create your views here.
import json
import os.path
import time

import numpy as np
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework import views, response
from scipy.linalg import solve

from ExtraXueHomepage.settings import LoggerConfig, BASE_DIR
# 日志
from Main.models import Calender

logger = LoggerConfig().mylogger_basic()
logger.getLogger(__name__)


def login(request):
    data = {
        'status': '200',
    }
    return HttpResponse(data['status'])


def fkl_index(request):
    home_path = os.path.join(BASE_DIR, 'static', 'dist', 'fkl-salary', 'fkl_index.html')
    return render(request, home_path)


def not_login_index(request):
    return HttpResponse("用户尚未登录，无法访问！")


@csrf_exempt
def get_data(request):
    print(request.POST.get("number"))
    return HttpResponse("200")


def isValidDate(date):
    try:
        if "-" in date:
            time.strptime(date, "%Y-%m-%d")
        else:
            time.strptime(date, "%Y%m%d")
        return True
    except:
        return False


class UnknownException(Exception):
    def __init__(self, error_info):
        super().__init__(self)  # 初始化父类
        self.error_info = error_info

    def __str__(self):
        return self.error_info


class CalDateView(views.APIView):

    @staticmethod
    @csrf_exempt
    def get(request):
        cal_date_type = request.GET.get("cal_date_type")
        input_date = request.GET.get("date")
        logger.info("传入时间为：" + input_date)
        logger.info("计算时间类型为：" + cal_date_type)
        if not isValidDate(input_date):
            return response.Response({
                "res_code": 500,
                "res_message": "时间无效！"
            })
        this_year_month = time.strftime("%Y%m", time.localtime())
        if time.strftime("%Y%m", time.localtime()) != time.strftime("%Y%m", time.strptime(input_date, "%Y%m%d")):
            return response.Response({
                "res_code": 500,
                "res_message": "时间非当月！"
            })
        if cal_date_type == "join":

            logger.info("入职时间为：" + input_date)
            try:
                date_list = Calender.objects.filter(cal_date__startswith=this_year_month).filter(is_break=0).filter(
                    cal_date__gte=input_date)
                # 如果月初入职，本月工作时间大于21.75天就按21.75天算
                if len(date_list) > 21.75:
                    date_count = 21.75
                else:
                    date_count = len(date_list)
            except UnknownException:
                return response.Response({
                    "res_code": 500,
                    "res_message": "查询日期异常！！"
                })
        elif cal_date_type == "quit":
            logger.info("离职时间为：" + input_date)
            try:
                date_list = Calender.objects.filter(cal_date__startswith=this_year_month).filter(is_break=0).filter(
                    cal_date__lte=input_date)
                date_count = len(date_list)
            except UnknownException:
                return response.Response({
                    "res_code": 500,
                    "res_message": "查询日期异常！！"
                })
        else:
            return response.Response({
                "res_code": 500,
                "res_message": "不是有效的计算时间类型！"
            })

        return response.Response({
            "res_code": 200,
            "date_count": date_count,
            "res_message": "success",
        })


# 根据
def define_quick_deduction_factor(cal_number_tmp):
    percent = ''
    quick_deduction_factor = ''
    if cal_number_tmp <= 36000:
        percent = 0.03
        quick_deduction_factor = 0
    elif 36000 < cal_number_tmp <= 144000:
        percent = 0.1
        quick_deduction_factor = 2520
    elif 144000 < cal_number_tmp <= 300000:
        percent = 0.2
        quick_deduction_factor = 15920
    elif 300000 < cal_number_tmp <= 420000:
        percent = 0.25
        quick_deduction_factor = 31920
    elif 420000 < cal_number_tmp <= 660000:
        percent = 0.3
        quick_deduction_factor = 52920
    elif 660000 < cal_number_tmp <= 960000:
        percent = 0.35
        quick_deduction_factor = 85920
    elif cal_number_tmp > 960000:
        percent = 0.45
        quick_deduction_factor = 181920
    return percent, quick_deduction_factor


class CalTaxView(views.APIView):

    def post(self, request):

        # json_list_object = [{
        #     "uid": 1,
        #     "salary_need_tax_last_month": 52755.56,  # 累积应纳税所得额（截止上月）
        #     "wxyj": 1575,  # 五险一金
        #     "tax_paid_last_month": 2755.56,  # 累积应纳税额（截止上月）
        #     "real_paid": 30000,  # 实发
        # }]
        json_list_object = request.data

        def cal_numbers(uid, salary_need_tax_last_month, wxyj, tax_paid_last_month, real_paid, percent,
                        quick_deduction_factor):
            personal_tax_limit = 5000  # 个税起征点
            # salary_need_tax_last_month  累积应纳税所得额（截止上月）
            # wxyj 五险一金
            # tax_paid_last_month 累积应纳税额（截止上月）
            # real_paid 实发
            # percent 速算比例
            # quick_deduction_factor 速算扣除数

            a = np.array([[-1, 1, 0, 0], [0, percent, -1, 0], [0, 0, 1, -1], [1, 0, 0, -1]])
            b = np.array(
                [salary_need_tax_last_month - wxyj - personal_tax_limit, quick_deduction_factor, tax_paid_last_month,
                 real_paid + wxyj])
            x = solve(a, b)

            tax_dict = {
                "uid": uid,
                # 税前工资
                "salary_before_tax": x.tolist()[0],
                # 应纳税所得额（截止本月）
                "salary_need_tax_this_month": x.tolist()[1],
                # 累计应纳税额（截止本月）
                "tax_paid_this_month": x.tolist()[2],
                # 当月实际应交税额
                "tax_need_to_pay_this_month": x.tolist()[3]
            }
            logger.info("uid = %i 计算后的各项金额为：%s", uid, json.dumps(tax_dict))
            return tax_dict

        return_list = []

        for val in json_list_object:

            uid = val['uid']
            salary_need_tax_last_month = val['salary_need_tax_last_month']
            wxyj = val['wxyj']
            tax_paid_last_month = val['tax_paid_last_month']
            real_paid = val['real_paid']

            # 把【实发-5000+上个月应纳税所得额】当做确定个税档位的参考值，先进行一遍计算,得到本月的应纳税所得额，根据这个额度确定最终的
            cal_number_tmp = real_paid - 5000 + salary_need_tax_last_month

            logger.info("cal_number_tmp: %i", cal_number_tmp)

            percent, quick_deduction_factor = define_quick_deduction_factor(cal_number_tmp)

            print(percent)

            logger.info("速算扣除数：%s", quick_deduction_factor)

            dict_object = cal_numbers(uid, salary_need_tax_last_month, wxyj, tax_paid_last_month, real_paid, percent,
                                      quick_deduction_factor)

            percent_2nd, quick_deduction_factor_2nd = define_quick_deduction_factor(
                dict_object["salary_need_tax_this_month"])

            if percent != percent_2nd or quick_deduction_factor != quick_deduction_factor_2nd:
                logger.info("uid = %s 税率档位预估错误！需要重新计算！...", uid)
                logger.info("uid = %s 第一次计算税率：%s，速算扣除数：%s ;第二次计算税率：%s，速算扣除数：%s", uid, percent, quick_deduction_factor,
                            percent_2nd, quick_deduction_factor_2nd)
                dict_object = cal_numbers(uid, salary_need_tax_last_month, wxyj, tax_paid_last_month, real_paid,
                                          percent_2nd, quick_deduction_factor_2nd)
            logger.info(dict_object)

            return_list.append(dict_object)

        logger.info("最终返回json串为：%s", return_list)
        return response.Response({
            "res_code": 200,
            "res_message": "success",
            "res_body": return_list
        })
